package com.cash.app.ui.main.fg.account

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import coil3.load
import coil3.request.placeholder
import coil3.request.transformations
import coil3.transform.CircleCropTransformation
import com.cash.app.R
import com.cash.app.custom.CommonDialog
import com.cash.app.custom.ContactInfoView
import com.cash.app.databinding.FgAccountBinding
import com.cash.app.manager.AccountInfoManager
import com.cash.app.manager.GlobalConfigManager
import com.cash.app.manager.LoginManager
import com.cash.app.ui.auth.AuthActivity
import com.cash.app.ui.login.LoginActivity
import com.cash.app.ui.order.LoanListActivity
import com.cash.app.ui.other.FeedbackActivity
import com.cash.app.ui.start.PolicyActivity

class AccountFragment(private val startSettingActivity: (() -> Unit)? = null) : Fragment() {

    private val ID_MY_LOAN = 0
    private val ID_MY_INFO = 1
    private val ID_FEEDBACK = 2
    private val ID_CONTACT_US = 3
    private val ID_POLICY = 4
    private val ID_SETTING = 5

    private var _binding: FgAccountBinding? = null
    private val binding get() = _binding!!

    private lateinit var menuContainer: ViewGroup
    private val accountItems = mutableListOf<AccountMenuItem>()

    private var _accountViewModel: AccountViewModel? = null
    private val accountViewModel get() = _accountViewModel!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _accountViewModel = ViewModelProvider(this)[AccountViewModel::class.java]
        _binding = FgAccountBinding.inflate(inflater, container, false)
        val root: View = binding.root
        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        menuContainer = view.findViewById(R.id.ll_menu_container)
        setupMenuItems()
        renderMenuItems()
        initObserver()
    }

    override fun onResume() {
        super.onResume()
        accountViewModel.getAccountDetail()
    }

    private fun initObserver() {
        accountViewModel.accountDetail.observe(viewLifecycleOwner) { data ->
            setAccountData()
        }
        accountViewModel.emptyInfo.observe(viewLifecycleOwner) { isLoad ->
            setAccountData()
        }
    }

    private fun setAccountData() {
        val name = AccountInfoManager.getUserMobileNumber()
        binding.tvUserName.text = name
        val headUrl = AccountInfoManager.getHeadImageUrl()
        if (headUrl.isNotEmpty()) {
            binding.avatarIv.load(headUrl) {
                transformations(CircleCropTransformation())
                placeholder(R.mipmap.momo)
            }
        }
    }

    private fun jumpToPage(itemId: Int, needLogin: Boolean = false) {
        if (needLogin) {
            if (!LoginManager.isLogin()) {
                LoginActivity.start(requireContext())
                return
            }
        }
        when (itemId) {
            ID_MY_LOAN -> {
                val intent = Intent(requireContext(), LoanListActivity::class.java)
                startActivity(intent)
            }

            ID_MY_INFO -> {
                val intent = Intent(requireContext(), AuthActivity::class.java)
                startActivity(intent)
            }

            ID_FEEDBACK -> {
                val intent = Intent(requireContext(), FeedbackActivity::class.java)
                startActivity(intent)
            }

            ID_POLICY -> {
                val intent = Intent(requireContext(), PolicyActivity::class.java).apply {
                    putExtra(PolicyActivity.EXTRA_SHOW_BOTTOM, false)
                }
                startActivity(intent)
            }

            ID_SETTING -> {
                // val intent = Intent(requireContext(), SettingActivity::class.java)
                // startActivity(intent)
                startSettingActivity?.invoke()
            }
        }
    }

    private fun setupMenuItems() {
        accountItems.clear()
        accountItems.addAll(
            listOf(
                AccountMenuItem(
                    id = ID_MY_LOAN,
                    title = getString(R.string.account_my_loan),
                    icon = R.mipmap.myloan
                ) {
                    jumpToPage(ID_MY_LOAN, needLogin = true)
                }, AccountMenuItem(
                    id = ID_MY_INFO,
                    title = getString(R.string.account_my_information),
                    icon = R.mipmap.myinformation
                ) {
                    jumpToPage(ID_MY_INFO, needLogin = true)
                }, AccountMenuItem(
                    id = ID_FEEDBACK,
                    title = getString(R.string.account_feedback),
                    icon = R.mipmap.feekbook
                ) {
                    jumpToPage(ID_FEEDBACK, needLogin = true)
                }, AccountMenuItem(
                    id = ID_CONTACT_US,
                    title = getString(R.string.account_contact_us),
                    icon = R.mipmap.kefu
                ) {
                    showContactDialog()
                }, AccountMenuItem(
                    id = ID_POLICY,
                    title = getString(R.string.account_privacy_policy),
                    icon = R.mipmap.privacypolicy
                ) {
                    jumpToPage(ID_POLICY)
                }, AccountMenuItem(
                    id = ID_SETTING,
                    title = getString(R.string.account_setting),
                    icon = R.mipmap.setting
                ) {
                    jumpToPage(ID_SETTING)
                })
        )
        if (!GlobalConfigManager.showContactUs()) {
            accountItems.removeAt(ID_CONTACT_US)
        }
    }

    private fun renderMenuItems() {
        menuContainer.removeAllViews()
        accountItems.forEachIndexed { index, accountItem ->
            val itemView = LayoutInflater.from(context).inflate(
                R.layout.fg_account_item, menuContainer, false
            ) as ConstraintLayout

            when (index) { // fix bg
                0 -> {
                    itemView.setBackgroundResource(R.drawable.account_item_bg_first)
                }

                accountItems.size - 1 -> {
                    itemView.setBackgroundResource(R.drawable.account_item_bg_last)
                }

                else -> {
                    itemView.setBackgroundResource(R.drawable.account_item_bg)
                }
            }
            itemView.findViewById<TextView>(R.id.tv_title).text = accountItem.title
            accountItem.icon.let { iconRes ->
                itemView.findViewById<ImageView>(R.id.iv_icon).setImageResource(iconRes)
            }

            itemView.setOnClickListener { accountItem.onClick.invoke() }
            menuContainer.addView(itemView)

        }
    }

    private fun showContactDialog() {
        // Create contact info view
        val contactInfoView = ContactInfoView(requireContext()).apply {
            setContactInfo(
                email = GlobalConfigManager.getEmailAddress(),
                whatsApp = GlobalConfigManager.getWhatsApp1(),
                whatsApp2 = GlobalConfigManager.getWhatsApp2()
            )
        }

        // Show dialog with contact info
        CommonDialog.Builder(requireContext()).setTitle(getString(R.string.app_contact_us))
            .setContentView(contactInfoView).showTitle(true).showButtons(true)
            .addButton(getString(R.string.cancel), { dialog ->
                dialog.dismiss()
            }).setCancelable(true).setCancelableOnTouchOutside(true).build().show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

/**
 * Data class representing a menu item in the account fragment
 */
data class AccountMenuItem(
    val id: Int, val title: String, val icon: Int, val onClick: () -> Unit
)